<template>
    <el-dialog
        :title="title"
        :modal-append-to-body="true"
        :append-to-body="true"
        custom-class="RecordDialog"
        :close-on-click-modal="false"
        v-model:visible="dialogVisible"
    >
        <template v-slot:default>
            <el-alert v-if="isDetail" title="为了安全，商品记录暂时只能修改备注" type="warning"></el-alert>
            <el-form
                label-position="right"
                label-width="80px"
                :rules="rules"
                ref="form"
                :model="ruleForm"
            >
                <el-form-item label="会员姓名" prop="userName">
                    <el-select :disabled="isDetail" v-model="ruleForm.userName" placeholder="请选择会员">
                        <el-option
                            v-for="item in tool.user"
                            :label="`${item.name} / ${item.phone}`"
                            :key="item.id"
                            :value="item.id" />
                    </el-select>
                </el-form-item>

                <el-form-item v-if="!isDetail" label="消费商品" prop="commodityName">
                    <div v-for="(comm, cindex) in commodityList" :key="comm.index" class="commodity">
                        <el-select
                                @change="commodityListChange"
                                v-model="comm.id"
                                filterable
                                placeholder="请选择商品">
                            <el-option
                                v-for="item in tool.commodity"
                                :label="`${item.name} (${item.unitPrice}元/个)`"
                                :key="item.id"
                                :value="item.id" />
                        </el-select>
                        <i class="el-icon-close"></i>
                        <el-input @change="commodityListChange" type="number" v-model="comm.number" />
                        个
                        <el-button v-if="commodityList.length > 1" @click="delCommodityList(cindex)" class="del_commodity" icon="el-icon-remove-outline" circle size="mini"></el-button>
                    </div>
                    <div class="add_commodity">
                        <el-button @click="addCommodityList" class="add_commodity" icon="el-icon-circle-plus-outline"></el-button>
                    </div>
                </el-form-item>
                <el-form-item v-else label="商品快照">
                    <ul>
                        <li v-for="l in commodityList">{{ `${l.name} (${l.unitPrice}元/个)` }}<i class="el-icon-close"></i>{{l.number}}</li>
                    </ul>
                </el-form-item>

                <el-form-item label="实收金额" prop="net">
                    <el-input :disabled="isDetail" v-model="ruleForm.net" type="number"></el-input>
                </el-form-item>
                <el-form-item label="增加积分" prop="integral">
                    <el-input :disabled="isDetail" v-model="ruleForm.integral" type="number"></el-input>
                </el-form-item>
                <el-form-item label="备注/描述" prop="remarks">
                    <el-input v-model="ruleForm.remarks" type="textarea" :rows="2"></el-input>
                </el-form-item>
            </el-form>

        </template>

        <template v-slot:footer>
            <span class="dialog-footer">
              <el-button @click="resetForm">取 消</el-button>
              <el-button type="primary" @click="submitForm">确 定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script>
import { reactive, toRefs, ref, computed } from 'vue'
import { addRecord, editRecord, getCommodity, getUser } from "../../api/api";
import { Message } from 'element3'

export default {
    name: 'RecordDialog',
    emits: ['ok'],
    props: {
        title: {
            type: String,
            default: '新增记录'
        }
    },
    setup(props, refs) {
        const dialogVisible = ref(false)
        const isDetail = ref(false)
        const form = ref(null)
        const ruleForm = reactive({
            ruleForm: {
                id: null,
                commodityName: '', // 商品名称
                userName: '', // 用户姓名手机
                net: '', // 金额
                integral: '', // 积分
                remarks: '' // 备注
            }
        })
        const double = computed(()=>{
            return count.value* 2;
        })
        const rules = reactive({
            rules: {
                userName: [
                    { required: true, message: '请输入姓名', trigger: 'blur' }
                ]
            }
        })

        const commodityList = reactive([{
            index: 1, // for 循环用的唯一值, 前端用的到的唯一值，剩下的都是详情描述用到的字段
            number: 1, // 数量
            id: '', // 商品id
            name: '', // 商品名称
            remarks: '', // 商品备注
            unitPrice: '' // 单价
        }])
        const tool = reactive({
            commodity: {},
            user: {}
        })
        function commodityListChange() {
            const count = commodityList.reduce((total, i) => {
                const b = tool.commodity[i.id]
                if (b) {
                    const c = b.unitPrice / 1 * i.number
                    return total + c
                }
                return total
            }, 0);
            ruleForm.ruleForm.net = count; // 金额
            ruleForm.ruleForm.integral = count; // 金额
        }
        function open(obj) {
            resetForm()
            dialogVisible.value = true
            getCommodity({ name: '', page: 1, size: 1000000 }).list.forEach(i => {
                tool.commodity[i.id] = i
            })
            getUser({ query: {}, page: 1, size: 1000000 }).list.forEach(i => {
                tool.user[i.id] = i
            })
            if (obj) {
                ruleForm.ruleForm = {...obj}
                ruleForm.ruleForm.userName = obj.userId
                commodityList.length = 0
                obj.commodity.forEach((t, i) => {
                    commodityList.push({
                        index: i,
                        ...t
                    })
                })
                isDetail.value = true
            } else {
                ruleForm.ruleForm.id = null
            }
        }
        function submitForm() {
            form.value.validate((valid) => {
                if (valid) {
                    const { id } = ruleForm.ruleForm
                    const commodity = []
                    commodityList.forEach(i => {
                        if (tool.commodity[i.id]) {
                            commodity.push({
                                ...tool.commodity[i.id],
                                number: i.number
                            })
                        }
                    })
                    const param = {
                        id,
                        commodity,
                        user: ruleForm.ruleForm.userName,
                        net: ruleForm.ruleForm.net, // 金额
                        integral: ruleForm.ruleForm.integral, // 积分
                        remarks: ruleForm.ruleForm.remarks // 备注
                    }
                    if (id || id === 0) {
                        editRecord(param)
                    } else {
                        addRecord(param)
                    }
                    refs.emit('ok')
                    Message({
                        message: '保存成功！',
                        type: 'success'
                    })
                    resetForm()

                }
            })
        }
        function resetForm() {
            dialogVisible.value = false
            isDetail.value = false
            ruleForm.ruleForm.id = null
            if (form.value) {
                form.value.resetFields()
            }
            ruleForm.ruleForm = {
                id: null,
                commodityName: '', // 商品名称
                userName: '', // 用户姓名手机
                net: '', // 金额
                integral: '', // 积分
                remarks: '' // 备注
            }
            commodityList.length = 0
            commodityList.push({
                index: 1, // for 循环用的唯一值, 前端用的到的唯一值，剩下的都是详情描述用到的字段
                number: 1, // 数量
                id: '', // 商品id
                name: '', // 商品名称
                remarks: '', // 商品备注
                unitPrice: '' // 单价
            })
        }
        function addCommodityList() {
            const last = commodityList[commodityList.length -1]
            commodityList.push({
                index: last.index + 1, // for 循环用的唯一值, 前端用的到的唯一值，剩下的都是详情描述用到的字段
                number: 1, // 数量
                id: '', // 商品id
                name: '', // 商品名称
                remarks: '', // 商品备注
                unitPrice: '' // 单价
            })
            console.log(commodityList);
        }
        function delCommodityList(index) {
            commodityList.splice(index, 1)
        }
        return {
            commodityList,
            delCommodityList,
            addCommodityList,
            commodityListChange,
            dialogVisible,
            form,
            tool,
            ...toRefs(ruleForm),
            ...toRefs(rules),
            isDetail,
            open,
            submitForm,
            resetForm
        }
    }
}
</script>

<style lang="less" scoped>
.commodity {
    margin-bottom: 10px;
    .el-button.del_commodity {
        padding: 0;
        font-size: 26px;
        color: rgb(220, 223, 230);
        vertical-align: middle;
        border: none;
        margin-left: 7px;
    }
    .el-select {
        width: 150px;
    }
    .el-input {
        width: 50px;
        /deep/ .el-input__inner {
            padding: 0 5px;
        }
    }
}
.add_commodity {
    text-align: center;
    button {
        margin-left: -50px;
        font-size: 25px;
        padding: 5px 20px;
        border: none;
    }

}
/deep/ .RecordDialog {
    .el-dialog__body {
        padding-top: 0;
    }
}
.el-alert {
    margin-bottom: 30px;
}
ul {
    padding-left: 16px;
    li {
        list-style: none;
    }
}
</style>
